/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-02-23 10:37:56
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-19 09:47:53
 * @Description: file content
 */
// import { Context } from "egg";
import { __awaiter } from "tslib";
import { FuncController as Controller } from "../../../libs/controller/Common";

import { batchRolePermission } from "../../service/sys/permission";

/**
 *系统 -> 角色 控制器
 *
 * @export
 * @class SysUserController
 * @extends {Controller}
 */
export default class PermissonController extends Controller {
  model = this.app.model.Sys.PermissionList;

  util_formatter(args, method) {
    if (method === "create") {
      args.body.create_user_id = this.ctx.loginUserInfo.uid;
    } else if (method === "update") {
      args.body.edit_user_id = this.ctx.loginUserInfo.uid;
    }
    return args;
  }

  /** 搜索获取列表 */
  async getSearchData() {
    const page: [number, number] = this.ctx.request.body.page || [20, 0];

    const allUser = await this.app.model.Sys.PermissionList.findAndCountAll({
      raw: false,
      limit: page[0],
      offset: page[1],
      attributes: {
        // 加上用户表的真实姓名字段。
        include: [
          [this.app.model.Sequelize.col("menu_perm.title"), "menu_title"],
        ],
      } as any,
      include: [
        {
          model: this.app.model.Sys.Menus,
          as: "menu_perm",
          attributes: [],
        },
      ],
    });
    this.ctx.success(allUser);
  }

  /** 获取某个菜单名下的所有自定义权限列表 */
  async getListByMenuId() {
    const menu_id = this.ctx.params.menu_id;
    const data = await this.ctx.model.Sys.PermissionList.findAll({
      raw: true,
      where: {
        menu_id: menu_id,
      },
    });
    this.ctx.success(data);
  }

  /** 批量添加角色权限功能。（将原来的全部删除，再添加） */
  async batchSetRolePermission() {
    const data: batchRolePermission = this.ctx.request.body;
    const ret = await this.ctx.service.sys.permission.batchPostRolesPermission(
      data
    );
    this.ctx.success(ret);
  }

  /** 根据角色的id获取其所有权限，并做成统一格式对象。增改查时的对象。 */
  async getAllPermByRoleId() {
    const role_id = this.ctx.params.role_id;
    if (role_id) {
      const ret = await this.ctx.service.sys.permission.getAllPermByRoleId(
        role_id
      );
      this.ctx.success(ret);
    }
  }

  /** 获取一个用户的权限表 */
  async getAllPermByUser() {
    const user_id = this.ctx.loginUserInfo.uid as number;
    const ret = await this.ctx.service.sys.permission.getAllPermByUser(user_id);
    // console.log(ret);
    this.ctx.success(ret);
  }
}
